from django_redis import get_redis_connection
from redis import RedisError
from rest_framework import serializers
import logging

logger = logging.getLogger('meiduo')


# 校验短信验证码序列化器
class RegisterSMSCodeSerializer(serializers.Serializer):
    text = serializers.CharField(label='验证码', max_length=4, min_length=4, required=True)
    image_code_id = serializers.UUIDField(label='验证码唯一标识')

    def validate(self, attrs):
        text = attrs['text']
        image_code_id = attrs['image_code_id']
        redis_conn = get_redis_connection('code')
        redis_text = redis_conn.get('img_%s' % image_code_id)
        if redis_text is None:
            raise serializers.ValidationError('图片验证码已过期')
        # 删除验证码， 减少内存消耗
        try:
            redis_conn.delete('img_%s' % image_code_id)
        except RedisError as e:
            logger.error(e)
        # 验证吗是bytes， 要解码
        if redis_text.decode().lower() != text:
            raise serializers.Serializer('图片验证码错误')
        return attrs

